/** Description of GraphBrand.java 
 *
 * @author panther
 * Jayant Pratim Saikia
 * jay.saikia@gmail.com
 *
 */
package com.panther.awp.android.smoker.activities.graphs;

import java.text.DecimalFormat;
import java.text.FieldPosition;
import java.text.Format;
import java.text.ParsePosition;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.TextView;

import com.androidplot.Plot;
import com.androidplot.xy.BarFormatter;
import com.androidplot.xy.BarRenderer;
import com.androidplot.xy.BoundaryMode;
import com.androidplot.xy.SimpleXYSeries;
import com.androidplot.xy.XYPlot;
import com.androidplot.xy.XYStepMode;
import com.panther.awp.android.smoker.R;
import com.panther.awp.android.smoker.database.AbstractDbAdapter;
import com.panther.awp.android.smoker.database.MyDBWrapper;

public class GraphBrand extends Activity {
	
	private XYPlot mBrandsBarPlot;
	private XYPlot mBrandsPricePlot;
	private SimpleXYSeries mBrandsSeries;
	private SimpleXYSeries mBrandsPriceSeries;
	private MyDBWrapper myDBWrapper;
	private HashMap<Number,Number> ciggCountHMap;
	private HashMap<Number, Number> ciggCostHMap;
	private HashMap<Number,String> ciggNameHMap;
	private int lowerlimitCount = Integer.MAX_VALUE;
	private int upperlimitCount = 0;
	private float lowerlimitCost = Float.MAX_VALUE;
	private float upperlimitCost = 0f;
	private TextView myCountText;
	private int totalCount = 0;
	private float totalCost = 0f;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.brandplot);
		myDBWrapper = MyDBWrapper.getInstance(getApplicationContext());
		mBrandsBarPlot = (XYPlot) findViewById(R.id.myBrandBarPlot);
		mBrandsPricePlot = (XYPlot) findViewById(R.id.myBrandBarPricePlot);
		myCountText = (TextView) findViewById(R.id.total_Smoked_Cigs);
		getData();
		mBrandsBarPlot.addSeries(mBrandsSeries, BarRenderer.class, new BarFormatter(Color.argb(100, 0, 200, 0), Color.rgb(0, 80, 0)));
		mBrandsPricePlot.addSeries(mBrandsPriceSeries, BarRenderer.class, new BarFormatter(Color.argb(100, 0, 200, 0), Color.rgb(0, 80, 0)));
		setPlotProperties();
		myCountText.setText("You have smoked " + totalCount + " cigarettes and it has cost you " + totalCost + " bucks.");
	}


	private void setPlotProperties() {
		
		mBrandsBarPlot.setDomainStep(XYStepMode.INCREMENT_BY_VAL, 1);
		mBrandsBarPlot.setTicksPerRangeLabel(3);
		mBrandsBarPlot.setRangeStep(XYStepMode.INCREMENT_BY_VAL, 1);
		mBrandsBarPlot.setRangeBoundaries(lowerlimitCount == 0 ? 0 : lowerlimitCount - 1, upperlimitCount + 1, BoundaryMode.FIXED);
		mBrandsBarPlot.setDomainValueFormat(new BrandIndexFormat());
		mBrandsBarPlot.setRangeValueFormat(new DecimalFormat("#"));
		mBrandsBarPlot.setDomainLabel("Brands");
		mBrandsBarPlot.getDomainLabelWidget().pack();
		mBrandsBarPlot.setRangeLabel("# of Ciggaretes");
		mBrandsBarPlot.getRangeLabelWidget().pack();
		mBrandsBarPlot.setGridPadding(10, 0, 10, 0);
		mBrandsBarPlot.setPlotMargins(0, 0, 0, 0);
		//mBrandsBarPlot.setPlotPadding(0, 0, 0, 0);
		mBrandsBarPlot.getGraphWidget().setMarginTop(2);
		mBrandsBarPlot.getGraphWidget().setMarginRight(2);
		mBrandsBarPlot.setBorderStyle(Plot.BorderStyle.SQUARE, null, null);
		mBrandsBarPlot.disableAllMarkup();
		
		BarRenderer barRenderer = (BarRenderer) mBrandsBarPlot.getRenderer(BarRenderer.class);
        if(barRenderer != null) {
            // make our bars a little thicker than the default so they can be seen better:
            barRenderer.setBarWidth(20);
        }
        
        if(ciggCountHMap.size() == 1) {
        	mBrandsBarPlot.setDomainBoundaries(0, 2, BoundaryMode.FIXED);
			mBrandsPricePlot.setDomainBoundaries(0, 2, BoundaryMode.FIXED);
		}
        
        mBrandsPricePlot.setDomainStep(XYStepMode.INCREMENT_BY_VAL, 1);
        mBrandsPricePlot.setTicksPerRangeLabel(4);
        mBrandsPricePlot.setRangeBoundaries(lowerlimitCost == 0 ? 0 : lowerlimitCost - 1, upperlimitCost + 1, BoundaryMode.FIXED);
		mBrandsPricePlot.setDomainValueFormat(new BrandIndexFormat());
		mBrandsPricePlot.setDomainLabel("Brands");
		mBrandsPricePlot.getDomainLabelWidget().pack();
		mBrandsPricePlot.setRangeLabel("Money Paid");
		mBrandsPricePlot.getRangeLabelWidget().pack();
		mBrandsPricePlot.setGridPadding(10, 0, 10, 0);
		mBrandsPricePlot.setPlotMargins(0, 0, 0, 0);
		//mBrandsPricePlot.setPlotPadding(0, 0, 0, 0);
		mBrandsPricePlot.getGraphWidget().setMarginTop(2);
		mBrandsPricePlot.getGraphWidget().setMarginRight(2);
		mBrandsPricePlot.setBorderStyle(Plot.BorderStyle.SQUARE, null, null);
		mBrandsPricePlot.disableAllMarkup();
		
		BarRenderer barRendererPrice = (BarRenderer) mBrandsPricePlot.getRenderer(BarRenderer.class);
        if(barRendererPrice != null) {
            // make our bars a little thicker than the default so they can be seen better:
        	barRendererPrice.setBarWidth(20);
        }
	}


	private void getData() {
		Cursor cursor = myDBWrapper.getmBTDbHelper().fetchAll();
		startManagingCursor(cursor);
		ciggCountHMap = new HashMap<Number, Number>();
		ciggNameHMap = new HashMap<Number, String>();
		ciggCostHMap = new HashMap<Number, Number>();
		cursor.moveToFirst();
		int barCount = 0;
		while (!cursor.isAfterLast()) {
			
			barCount++;
			int count = cursor.getInt(cursor.getColumnIndexOrThrow(AbstractDbAdapter.BT_NO_OF_CIGGS));
			float price = cursor.getFloat(cursor.getColumnIndexOrThrow(AbstractDbAdapter.BT_BRAND_PRICE));
			float cost = price*count;
			totalCost += cost;
			totalCount += count;
			ciggCountHMap.put(barCount, count);
			ciggCostHMap.put(barCount, cost);
			ciggNameHMap.put(barCount, cursor.getString(cursor.getColumnIndexOrThrow(AbstractDbAdapter.BT_BRAND)));
			lowerlimitCount = lowerlimitCount > count ? count : lowerlimitCount;
			upperlimitCount = upperlimitCount < count ? count : upperlimitCount;
			lowerlimitCost = lowerlimitCost > cost ? cost : lowerlimitCost;
			upperlimitCost = upperlimitCost < cost ? cost : upperlimitCost;
			
			cursor.moveToNext();
		}
		List<Number> ciggCountVals = new ArrayList<Number>(ciggCountHMap.values());
		List<Number> ciggIdVals = new ArrayList<Number>(ciggCostHMap.keySet());
		List<Number> ciggCostVals = new ArrayList<Number>(ciggCostHMap.values());
		mBrandsSeries = new SimpleXYSeries(ciggIdVals, ciggCountVals, "Brands Series");
		mBrandsPriceSeries = new SimpleXYSeries(ciggIdVals, ciggCostVals, "Brands Price Series");
	}
	
	private class BrandIndexFormat extends Format {

		private static final long serialVersionUID = 5133698491470068632L;

		@Override
		public StringBuffer format(Object object, StringBuffer buffer, FieldPosition field) {
			Number num = (Number) object;
			int roundNum = (int) (num.floatValue());
			if(ciggNameHMap.containsKey(roundNum)) {
				buffer.append(ciggNameHMap.get(roundNum));
			}
			return buffer;
		}

		@Override
		public Object parseObject(String string, ParsePosition position) {
			return null;
		}
		
	}

}
